#ifndef __STREAMSERVER_H_
#define __STREAMSERVER_H_
#include "ErrCode.h"
#include "OSQueue.h"
#include "OSMutex.h"
#include "TcpSocketServer.h"
#include "msg.h"
#include "V4L2CaptureThread.h"

#define MAX_CLIENT_NUM (5)
#define MAX_STREAM_SIZE (2 * 1024 * 1024)
#define MAX_EVER_SEND_LEN (36767)

struct StreamPackageHeader
{
    //包头大小(sizeof(StreamPackageHeader))
    unsigned int uPackageHeaderSize;
    //当前包头的大小(sizeof(StreamPackageHeader) + 当前数据包长度)
    unsigned int uCurrentTransPackageSize;
    //数据包的总大小
    unsigned int uTotalDataSize;
    //数据被分成包的个数
    unsigned int uDataPackageNum;
    //数据包当前的帧号
    unsigned int uDataPackageCurrIndex;
    //数据包在整个数据中的偏移
    unsigned int uDataPackageOffset;
};

typedef struct ClientInfo
{
    ConnNode* pClient;
    OSQueueElem elem;
    ClientInfo()
    {
        elem.SetEnclosingObject(this);
    }
}tClientInfo;

class StreamServer : public TcpSocketServer
{
private:
    tClientInfo m_ClientList[MAX_CLIENT_NUM];
    OSQueue m_WorkingQueue;
    OSQueue m_FreeQueue;
protected:
	//重载各个处理业务的虚函数
	void ReadEvent(ConnNode *conn);
	void WriteEvent(ConnNode *conn);
	void ConnectionEvent(ConnNode *conn);
	void CloseEvent(ConnNode *conn, short events);
public:
    StreamServer(int count);
    ~StreamServer();

    OS_Error SendToClient(msg_type t, char* pbody,int len);
    OS_Error SendToClient(char* pbody, int len);
    OS_Error SendStreamToClient(char* pbody, int len);
	//定时器事件，每10秒向所有客户端发一句hello, world
	static void TimeOutCb(int id, int short events, void *data);
    //发送心跳包的定时器回调
    static void HeartBeatCb(int id, int short events, void *data);
private:
    int PackageHttp(tClientInfo* pClientInfo,char* msg,int len);
    tClientInfo* Malloc();
    void Free(tClientInfo* pClientInfo);
    void Cleanup();
    void Parse(int msgtype);
private:
    V4L2CaptureThread m_v4l2Capture;
public:
    OSMutex m_mutex;
    char* m_msg;
    int m_msglen;
};
#endif
